package com.example.springdemo.datasource;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import tk.mybatis.spring.annotation.MapperScan;

import java.util.HashMap;

/**
 * @author wanghuajun
 * @version 1.0
 * @date 2019-08-09 22:09
 */
@Slf4j
@Configuration
@EnableTransactionManagement(order = 2)
@MapperScan(basePackages = {"com.example.springdemo.dao"})
public class MybatisTkConfig {

    @Autowired
    private DefaultDataSourceProperties defaultDataSourceProperties;

    @Autowired
    private MultipleDataSourceProperties multipleDataSourceProperties;

    /**
     * 默认数据源
     *
     * @return
     */
    private HikariDataSource defaultDataSource() {
        log.info("配置MybatisTkConfig#defaultDataSource");

        HikariDataSource hikariDataSource = new HikariDataSource();
        defaultDataSourceProperties.config(hikariDataSource);
        return hikariDataSource;
    }

    /**
     * content数据源
     *
     * @return
     */
    private HikariDataSource contentDataSource() {
        log.info("配置MybatisTkConfig#contentDataSource");

        HikariDataSource hikariDataSource = new HikariDataSource();
        multipleDataSourceProperties.config(hikariDataSource);
        return hikariDataSource;
    }

    /**
     * 单数据源连接池配置
     *
     * @return
     */
    @Bean
    @ConditionalOnProperty(prefix = "multiple-db", name = "datasource-open", havingValue = "false")
    //当配置文件中multiple-db开头的datasource-open的值为false的时候，该注解才生效
    public HikariDataSource singleDataSource() {
        log.info("配置MybatisTkConfig#singleDataSource");

        return defaultDataSource();
    }

    /**
     * 多数据源连接池配置
     *
     * @return
     */
    @Bean
    @ConditionalOnProperty(prefix = "multiple-db", name = "datasource-open", havingValue = "true")
    //当配置文件中multiple-db开头的datasource-open的值为true的时候，该注解才生效
    public DynamicDataSource multipleDataSource() {
        log.info("配置MybatisTkConfig#multipleDataSource");

        HikariConfig contentDataSource = contentDataSource();
        HikariConfig defaultDataSource = defaultDataSource();

        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        final HashMap<Object, Object> dbMap = new HashMap<>(2);
        dbMap.put(DB.USER_CENTER, defaultDataSource);
        dbMap.put(DB.CONTENT_CENTER, contentDataSource);
        dynamicDataSource.setTargetDataSources(dbMap);
        dynamicDataSource.setDefaultTargetDataSource(defaultDataSource);
        return dynamicDataSource;
    }

}
